<?php
/**
 * File containing the BRail_Ldap_GroupQueryTool class.
 * @package BRail_Ldap
 */

/**
 * @package BRail_Ldap
 */
class BRail_Ldap_GroupQueryTool
{
    /**
     * @var BRail_Ldap_Adapter $_ldapAdapter
     */
    private $_ldapAdapter = null;

    /**
     * @var array
     */
    private $_groups;

    /**
     * @param BRail_Ldap_Adapter $ldapAdapter
     */
    public function __construct(BRail_Ldap_Adapter $ldapAdapter)
    {
        $this->_ldapAdapter = $ldapAdapter;
    }

    /**
     * @param string $group
     * @return array
     */
    public function getNested($group)
    {
        $this->_groups = array();
        return $this->recursiveSearch($group);
    }

    /**
     * @param string $group
     * @return array
     */
    private function recursiveSearch($group)
    {
        $entries = $this->_ldapAdapter->execute(
            "(&(objectCategory=group)(cn=$group))",
            array("member", "objectClass")
        );
        if (isset($entries[0]) && $entries[0]['objectclass'][1] === 'group') {
            $this->_groups[] = $group;
            for ($i = 0; $i < $entries[0]['member']['count']; $i++) {
                $memberDetails = explode(',', $entries[0]['member'][$i]);
                $firstField = explode('=', $memberDetails[0]);
                $this->recursiveSearch($firstField[1]);
            }
        }
        return $this->_groups;
    }
}
